package network;
/**
 * This class is a linked list for holding the redundant server list for a Peer.
 * redundant lists are formated: <ip><port>
 * This means that there are 4/16 bytes (inet version) and then 2 for port.
 * @author jex
 *
 */
public class ServerList {
	//Use linked list, keep it sorted as we add items
	
	private volatile ServerLink root = null;
	private final int compare;
	private int length=0;
	
	public ServerList(int compare){
		this.compare = compare;
	}
	
	public synchronized void add(String[] s){
		for(String str : s){
			if(str != null){
				add(s);
			}
		}
	} 
	
	/**
	 * Compare IPs at front IP.Length chars of string, if it's already there, replace.
	 * Otherwise add it.
	 * @param n
	 * @return
	 */
	public synchronized void add(String n){
		if(n.length() < compare){
			return;
		}
		String s = n.substring(0,compare);
		ServerLink l = root;
		ServerLink p = root;
		if(root == null){
			length++;
			root = new ServerLink(n);
			return;
		}
		int sub = 0;
		ServerLink a = new ServerLink(n);
		while(l != null && l != a){
			sub = l.node.substring(0,compare).compareTo(s);
			if( sub == 0 ){
				a.before = l.before;
				a.after = l.after;
				if (a.before != null) {
					a.before.after = a;
				}
				if (a.after != null) {
					a.after.before = a;
				}
			}else if( sub > 0){
				//not here, stick it in before this one.
				a.before = l.before;
				a.after = l;
				if (a.before != null) {
					a.before.after = a;
				}
				if (a.after != null) {
					a.after.before = a;
				}
			}else if( sub < 0 && l.after == null){
				l.after = a;
				a.before = l;
				//might still be here...keep going
			}
			if( sub >= 0 ){
				if( l.equals(root) ){
					root = a;
				}
				break;
			}
			l = l.after;
		}
		if(sub != 0){
			length++;
		}
	}
	

	public String[] getList(){
		ServerLink n = root;
		String[] ret = new String[length];
		for(int i=0; i<length; i++){
			ret[i] = n.node;
			n = n.after;
		}
		return ret;
	}
	

}
class ServerLink {
	
	final String node;
	ServerLink before = null;
	ServerLink after = null;
	
	
	public ServerLink(String s){
		node = s;
	}
	public ServerLink(String s, ServerLink befor, ServerLink aftr){
		node = s;
		before = befor;
		after = aftr;
	}
	
}



